<!-- 
  悬浮弹窗组件
  功能说明
    显示弹窗：
        点击 #show 插槽内容时，弹窗会显示在触发区域下方
        弹窗位置会根据触发区域的高度自动调整
    关闭弹窗：
        方式1：点击弹窗外部区域（非弹窗内容）
        方式2：在 #footer 插槽中，可以通过作用域变量 close 来调用关闭弹窗的逻辑
    插槽要求：
        #show 插槽是必填的，用于触发弹窗
        #content 插槽是必填的，用于显示弹窗内容
        #footer 插槽是可选的，用于显示弹窗底部内容
-->
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const stickPopup = ref(null)
const stickPopupShow = ref(null)
const stickPopupPopup = ref(null)

onMounted(() => {
    // 监听stickPopup的hover事件
    stickPopupShow.value.addEventListener('click', () => {
        // 获取stickPopup的宽度和高度
        const stickPopupWidth = stickPopup.value.offsetWidth
        const stickPopupHeight = stickPopup.value.offsetHeight

        // stickPopupPopup根据stickPopup的高度进行定位
        stickPopupPopup.value.style.left = `0px`
        stickPopupPopup.value.style.top = `${stickPopupHeight}px`
        stickPopupPopup.value.style.display = 'block'
    })
    // 监听windows的点击事件, 如果点击的不是stickPopup, 则隐藏stickPopupPopup
    window.addEventListener('click', (e) => {
        if(!stickPopupPopup.value) return
        console.log(e.target)
        if (!stickPopup.value.contains(e.target)) {
            stickPopupPopup.value.style.display = 'none'
        }
    })
})
// 组件卸载时移除事件监听
onUnmounted(() => { 
    if(stickPopupShow.value) {
        stickPopupShow.value.removeEventListener('click', () => {})
    }
    window.removeEventListener('click', () => {})
})


const close = () => {
    stickPopupPopup.value.style.display = 'none'
}
</script>

<template>
    <div class="stick-popup" ref="stickPopup">
        <div class="stick-popup-show" ref="stickPopupShow">
            <slot name="show"></slot>
        </div>
        <div class="stick-popup-popup" ref="stickPopupPopup">
            <div class="stick-popup-content">
                <slot name="content"></slot>
            </div>
            <div class="stick-popup-footer">
                <slot name="footer" :close="close"></slot>
            </div>
        </div>
    </div>
</template>

<style lang="less" scoped>
.stick-popup {
    position: relative;
    .stick-popup-popup {
        position: absolute;
        display: none;
        max-height: 500px;
        overflow: auto;
        background-color: #fff;
        z-index: 10;
        box-shadow: 0 0 10px 0 #eee;
        padding: 10px;
        box-sizing: border-box;
        padding-bottom: 0;
        .stick-popup-footer {
            position: sticky;
            bottom: 0;
            left: 0;
            z-index: 5;
        }
    }
}
</style>